﻿' Frowser - http://www.frowser.net
' Copyright (c) 2010
' by Will Morgenweck, Active Modules, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
Imports System.Web.Services
Imports Active.Modules.Forums
Imports System.IO

Namespace Frowser.Services
    Public Class WebServiceBase
        Inherits System.Web.Services.WebService
        Public Enum ResultCodes
            Success
            FailedAuthentication
            FailedWithException
            FailedAccessKey
            FailedInvalidData
            FailedInvalidUser
            FailedInvalidGroup
            SuccessNoRecords
            FailedInvalidFile
            FailedFileNotAllowed
            SuccessAuthentication
        End Enum
        Public Enum OutputTypes
            XML
            JSON
        End Enum
        Public Property PortalId() As Integer
        Public Property PortalName() As String
        Public Property UserId() As Integer
        Public Property UserForums() As String = String.Empty
        Public Property ModuleId() As Integer = -1
        Public Property ServicePath() As String = String.Empty
        Public Property CurrentUser() As UserInfo
       
        ''' <summary>
        ''' 
        ''' </summary>
        ''' <remarks></remarks>
        Friend Sub Init()
            Dim DomainName As String = Nothing
            Dim objPortalAliasInfo As DotNetNuke.Entities.Portals.PortalAliasInfo = Nothing
            Dim sUrl As String = HttpContext.Current.Request.RawUrl.Replace("http://", String.Empty).Replace("https://", String.Empty)
            objPortalAliasInfo = DotNetNuke.Entities.Portals.PortalSettings.GetPortalAliasInfo(HttpContext.Current.Request.Url.Host)
            PortalId = objPortalAliasInfo.PortalID
            Dim pc As New DotNetNuke.Entities.Portals.PortalController
            Dim pi As DotNetNuke.Entities.Portals.PortalInfo = pc.GetPortal(PortalId)
            PortalName = pi.PortalName
            Dim config As String = GetFile(Server.MapPath("~/DesktopModules/Frowser/modules.resources"))
            If Not String.IsNullOrEmpty(config) Then
                Dim rows() As String = config.Split(CChar(ControlChars.NewLine))
                For Each s As String In rows
                    If Not String.IsNullOrEmpty(s) Then
                        Dim entries() As String = s.Split(CChar("|"))
                        If CInt(entries(0)) = PortalId Then
                            ModuleId = CInt(entries(1))
                            ServicePath = entries(2).ToString
                            Exit For
                        End If
                    End If
                Next
            End If
        End Sub
        ''' <summary>
        ''' 
        ''' </summary>
        ''' <param name="out"></param>
        ''' <param name="ResultCode"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Friend Function BuildResult(ByVal out As String, ByVal ResultCode As ResultCodes) As String
            Return BuildResult(out, ResultCode, OutputTypes.XML, False)
        End Function
        ''' <summary>
        ''' 
        ''' </summary>
        ''' <param name="out"></param>
        ''' <param name="resultCode"></param>
        ''' <param name="outputType"></param>
        ''' <param name="IsObject"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Friend Function BuildResult(ByVal out As String, ByVal resultCode As ResultCodes, ByVal outputType As OutputTypes, ByVal IsObject As Boolean) As String
            Dim sb As New StringBuilder
            If outputType = OutputTypes.XML Then
                If resultCode = 0 Then
                    sb.Append("<result success=""true"">")
                    sb.Append(out)
                Else
                    sb.Append("<result success=""false"">")
                    sb.Append("<error id=""" & CInt(resultCode).ToString & """>")
                    Select Case resultCode
                        Case ResultCodes.FailedAuthentication
                            sb.Append("Bad Username or Password")
                        Case ResultCodes.FailedWithException
                            sb.Append(out)
                        Case ResultCodes.FailedAccessKey
                            sb.Append("Invalid Access Key")
                        Case ResultCodes.FailedInvalidData
                            sb.Append("The data provided is not valid")
                        Case ResultCodes.FailedInvalidUser
                            sb.Append("The user specified is not valid")
                        Case ResultCodes.FailedInvalidGroup
                            sb.Append("The group specified is not valid")
                        Case ResultCodes.SuccessNoRecords
                            sb.Append("No Data Found")
                        Case ResultCodes.FailedInvalidFile
                            sb.Append("Unable to process the file")
                        Case ResultCodes.FailedFileNotAllowed
                            sb.Append("File Not Allowed")
                    End Select
                    sb.Append("</error>")
                End If
                sb.Append("</result>")
            Else
                sb.Append("[")
                If resultCode = 0 Then
                    sb.Append("{""success"":true")
                    If Not String.IsNullOrEmpty(out) Then
                        sb.Append(",")
                        If IsObject Then
                            sb.Append("""result"":[" & out & "]")
                        Else
                            sb.Append(Utilities.JSON.Pair("result", out, True))
                        End If

                    End If
                    sb.Append("}")
                Else
                    sb.Append("{""success"":false")
                    sb.Append(",")
                    Dim msg As String = "Not Specified"
                    Select Case resultCode
                        Case ResultCodes.FailedAuthentication
                            msg = "Bad Username or Password"
                        Case ResultCodes.FailedWithException
                            msg = out
                        Case ResultCodes.FailedAccessKey
                            msg = "Invalid Access Key"
                        Case ResultCodes.FailedInvalidData
                            msg = "The data provided is not valid"
                        Case ResultCodes.FailedInvalidUser
                            msg = "The user specified is not valid"
                        Case ResultCodes.FailedInvalidGroup
                            msg = "The group specified is not valid"
                        Case ResultCodes.SuccessNoRecords
                            msg = "No Data Found"
                        Case ResultCodes.FailedInvalidFile
                            sb.Append("Unable to process the file")
                        Case ResultCodes.FailedFileNotAllowed
                            sb.Append("File Not Allowed")
                    End Select
                    sb.Append(Utilities.JSON.Pair("message", msg))
                    sb.Append("}")



                End If

                sb.Append("]")
            End If


            Return sb.ToString


        End Function
      
        ''' <summary>
        ''' Get the template as a string from the specified path
        ''' </summary>
        ''' <param name="FilePath">Physical path to file</param>
        ''' <returns>String</returns>
        ''' <remarks></remarks>
        Friend Shared Function GetFile(ByVal FilePath As String) As String
            Dim sContents As String = String.Empty
            If IO.File.Exists(FilePath) Then
                Try
                    Using sr As IO.StreamReader = New StreamReader(FilePath, Encoding.UTF8)
                        sContents = sr.ReadToEnd()
                        sr.Close()
                    End Using
                Catch exc As Exception
                    sContents = exc.Message
                End Try
            End If
            Return sContents
        End Function
    End Class
    Public Class SecureHeader
        Inherits System.Web.Services.Protocols.SoapHeader
        Public Property Username() As String = String.Empty
        Public Property Password() As String = String.Empty
        Public Property AuthToken() As String = String.Empty
        Sub New()

        End Sub
        Sub New(ByVal authToken As String)
            Me.AuthToken = authToken
            Me.Username = String.Empty
            Me.Password = String.Empty
        End Sub
        Sub New(ByVal Username As String, ByVal Password As String)
            Me.AuthToken = String.Empty
            Me.Username = Username
            Me.Password = Password
        End Sub
        Sub New(ByVal authToken As String, ByVal Username As String, ByVal Password As String)
            If String.IsNullOrEmpty(authToken) Then
                Me.AuthToken = String.Empty
                Me.Username = Username
                Me.Password = Password
            Else
                Me.AuthToken = authToken
                Me.Username = String.Empty
                Me.Password = String.Empty
            End If
        End Sub
    End Class
End Namespace

